#include <stdio.h>
#include <assert.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h> 
#include <fcntl.h>
#include <unistd.h>
#define FILE_NAME "log.txt"
#define ONE (1<<0)
#define TWO (1<<1)
#define THREE (1<<2)
//比特位标识符
void show(int flags)
{
    if(flags & ONE) printf("one\n");    
    if(flags & TWO) printf("two\n");    
    if(flags & THREE) printf("three\n");    
}
void test_bit()
{
    show(ONE);
    puts("-----");
    show(ONE | TWO);
    puts("-----");
    show(ONE | TWO | THREE);
}
//测试c语言文件函数
void test_c_file_func()
{
    //r,w, r+(读写，文件不存在报错)，w+(读写，文件不存在创建)，a+(读写，在文件末尾读写)
    //以w的方式单纯打开文件，c会自动情况内部的数据
    /* umask(0);
    FILE* pf = fopen(FILE_NAME, "w");
    int cnt = 5;
    while(cnt)
    {
        fprintf(pf, "%s:%d\n", "hello world", cnt--);
    }
    fclose(pf); */
    FILE* pf = fopen(FILE_NAME, "r");
    char buffer[64];
    while(fgets(buffer, sizeof buffer, pf))
    {
        //把字符串末尾\n替换成\0
        buffer[strlen(buffer) - 1] = 0;
        puts(buffer);
    }
    fclose(pf);
}
void test_sys_file_func()
{
    umask(0);
    //c语言中的"w" -> O_WRONLY | O_CREAT | O_TRUNC, 0666
    //int fd = open(FILE_NAME, O_WRONLY | O_CREAT | O_TRUNC, 0666);
    //int fd = open(FILE_NAME, O_WRONLY | O_APPEND | O_CREAT, 0666);
    int fd = open(FILE_NAME, O_RDONLY);
    if(fd == -1)
    {
        perror("open");
        return;
    }
   // printf("fd: %d\n", fd); 
   // int cnt = 5; char buffer[64];
   // while(cnt)
   // {
   //     sprintf(buffer, "%s:%d\n", "aaaaa", cnt--);
   //     write(fd, buffer, strlen(buffer));
   // }
    char buffer[1024];
    ssize_t num = read(fd, buffer, sizeof(buffer) - 1);
    if(num > 0)
    {
        buffer[num] = 0;
    }
    puts(buffer);
    
    close(fd);
}
void test()
{
    int fd = open("example.txt", O_WRONLY | O_TRUNC | O_CREAT, 0666);
    char buffer[64] = "This is an apple";
    write(fd, buffer, strlen(buffer));
    lseek(fd, 9, SEEK_SET);
    char buffer_[64] = " sam";
    write(fd, buffer_, strlen(buffer_));
    close(fd);
}
int main()
{
    //test_bit();
    test_c_file_func();
    //test_sys_file_func();   
    test();
    printf("stdin->fd: %d\n", stdin->_fileno);
    printf("stout->fd: %d\n", stdout->_fileno);
    printf("stderr->fd: %d\n", stderr->_fileno);

    return 0;
}
